var _id,_specArr = [];
var login = false;
var total = 100;    //设置初始库存
var min = 1;
var pageNum = 1;
var shareId = '';
var buyType = "add-cart";

var a_url = window.location.href;
var a_title = '';
var a_desc = '';
var a_img = '';
var a_summary = '火匣生活';
var config = '';
var share_obj = '';

$(function(){

    _id = window.location.hash.replace("#","");

    //产品详情
    post({
        url:'/product/'+_id+'/detail',
        success:function(data){
            // console.log(data);
            dealData(data);
        }
    });


    post({
        url : "/isLogin",
        success : function(data){
            if(!data){
                login = false;
            }else{
                login = true;
                post({
                    url:"/member/uid",
                    success:function(data){
                        shareId = data;
                    }
                });
            }
        }
    });

    changeNum();//改变购买数量

    isScroll();

    //articleList(true);//专题文章列表

    //返回上一级
    $(".go-back").click(function(){
        var _url = decodeURIComponent(getCookie("productdetailgoback"));
        _url = _url?_url:"/index.html";
        go(_url);
    });

    $(".menu").on("click",function(){
        $("#bottom").toggleClass("tab");
    });

    //点击分享遮罩，隐藏分享icon
    $(".share_cover,.pay_container").click(function(){
        $(".wrap_share,.share_cover,.pay_container").addClass("tab");
    });

    //在公众号，点击微信朋友圈、好友等icon,显示提示引导页面
    $(".wrap_share .bottom").click(function(){
        $(".pay_container").removeClass("tab");
    });

    //点击底部“加入购物车”
    $(".add_cart .btn,.add_cart .buy-now").click(function(){
        buyType = $(this).data("type");
        if(buyType == "add-cart"){
            $(".c_main .btn").text("加入购物车");
        }else{
            $(".c_main .btn").text("立即购买");
        }
        $(".container").css("position","fixed");
        $(".c_container").css("display","block");
        $(".cover").animate({"opacity":"0.5"},"500");
        $(".c_main").animate({"bottom":"0%"},"500");
    });

    //点击关闭 选择规格页面
    $(".c_main .close").click(function(){
        $(".container").css("position","static");
        $(".c_main").animate({"bottom":"-120%"},"500");
        $(".cover").animate({"opacity":"0"},"500");
        setTimeout(function(){
            $(".c_container").css("display","none");
        },500)
    });

    //如果不是在微信，则删除 .bottom
    if(isWeiXin() == false){
        $(".wrap_share .bottom").remove();
    }

});


function dealData(data){
    // console.log(data)
    //商品主图
    var _img = '<div class="images swiper-container"><div class="swiper-wrapper">';
    for(var i=0;i<data["productPictures"].length;i++){
        _img += '<div class="swiper-slide"><img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data["productPictures"][i]+'"></div>';
    }
    _img += '</div><div class="swiper-pagination"></div></div>';
    _img += '<div class="info-left left">'

    _img +='<p class="more_single name">'+data.name+'</p><p class="c_price">￥<span>';
    _img += ''+parseInt(data.retailPrice)+'.</span>'+((data.retailPrice).toFixed(2).toString().split(".")[1])+'</p>'
    _img += '</div>';
    //修改
    _img += '<div class="info-right left"><a href="/usercomment/index.html#'+_id+'">查看</a>';
    _img += '<span>用户评价</span></div>';

    $(".wrap_main .main .info").html(_img);

    var mySwiper = new Swiper ('.info .swiper-container', {
        pagination: '.swiper-pagination',
        paginationElement : 'span',
        loop: true,//循环
        autoplay: 3000//播放间隔
    });

    zoomImg($('.info .swiper-slide img'),data["productPictures"]); // 查看放大图

    if(data.status == "SALE_LOWER"){ //已下架
        $(".add_cart .sale-lower").removeClass("tab");
        $(".add_cart .btn,.add_cart .buy-now").addClass("tab");
    }else{
        $(".add_cart .sale-lower").addClass("tab");
        $(".add_cart .btn,.add_cart .buy-now").removeClass("tab");
    }

    //商品详情
    var _attr = '<ul>';
    for(var j=0;j<data["productAttributes"].length;j++){
        _attr += '<li><span class="name left">'+data["productAttributes"][j]["attrName"]+'</span>';
        _attr += '<span class="value left">'+data["productAttributes"][j]["attrValue"]+'</span></li>';
    }
    _attr += '</ul>';

    $(".wrap_main .good_attribute").html(_attr);
    $(".wrap_main .good_detail").html((data.content).replace(/\/load\/picture\//g,SERVER_CONTEXT_PATH+"/load/picture/"));

    $(".wrap_main .wrap_bottom .title li:nth-child(1)").click(function(){
        $(".wrap_main .wrap_bottom .title li").removeClass("selected");
        $(this).addClass("selected");
        $(".wrap_main .good_detail").css("display","block");
        $(".wrap_main .good_attribute,.wrap_main .life").css("display","none");
    });

    $(".wrap_main .wrap_bottom .title li:nth-child(2)").click(function(){
        $(".wrap_main .wrap_bottom .title li").removeClass("selected");
        $(this).addClass("selected");
        $(".wrap_main .good_detail,.wrap_main .life").css("display","none");
        $(".wrap_main .good_attribute").css("display","block");
    });

    $(".c_detail .img img").attr("src",SERVER_CONTEXT_PATH+"/load/picture/"+data.imageUrl);

    //规格
    var _spec = '';
    for(var k=0;k<data["specifications"].length;k++){
        _spec += '<li><p>'+data["specifications"][k]["name"]+'<a>(请选择)</a></p>';
        for(var n=0;n<data["specifications"][k]["specValues"].length;n++){
            _spec += '<span data-id="'+data["specifications"][k]["specValues"][n]["id"]+'">';
            _spec += ''+data["specifications"][k]["specValues"][n]["specValue"]+'</span>';
        }
        _spec += '</li>';
        _specArr.push('');
    }

    $(".specification ul").html(_spec);
    $(".c_detail .price").html('价格：<span>￥'+(data.retailPrice).toFixed(2)+'</span>');

    specification();//选择规格
    getCartNum();//读取购物车商品数量

}

//重置样式
function reset(){
    var _h = $("#bottom").height();
    $(".c_main .btn,.add_cart").css("bottom",_h+1+"px");
    $(".c_main .specification").css("bottom",_h+$(".btn").height()+3+"px");
    $(".bottom_space").height($(".add_cart").height()+_h);
}

//选择规格
function specification(){

    var _arr = [];
    $(".specification li").each(function(i){
        _arr[i] = "";
        $(this).find("span").click(function(){
            if(!!$(this).hasClass("red_back")){
                $(this).removeClass("red_back");
                _arr[i] = "";
                _specArr[i] = '';
            }else{
                _arr[i] = $(this).text();
                $(this).addClass("red_back").siblings("span").removeClass("red_back");
                _specArr[i] = $(this).data("id");
            }
            showSpec(_arr);
            getPrice(_specArr);
        });
    });
}

//读取购物车数量
function getCartNum(){

    post({
        url:"/cart/list",
        success:function(_data){
            var num = 0;
            for(var n=0;n<_data.length;n++){
                num += _data[n]["num"];
            }
            if(num<100){
                $(".icon_cart p").text(num);
            }else{
                $(".icon_cart p").text("99+");
            }
        }
    })
}

//点击选择规格页面的 “加入购物车”
$(".c_main .btn").click(function(){
    if(isEmpty(_specArr)){ //判断是否已选择规格
        if(login){//判断是否已登录
            if(total>0){//判断是否有库存
                if(buyType == "add-cart"){  //加入购物车
                    post({
                        url:"/cart/save",
                        data:{productId:_id,specGroup:_specArr.toString(),num:$(".num .middle input").val()},
                        success:function(data){
                            $(".c_main").animate({"bottom":"-120%"},"500");
                            $(".cover").animate({"opacity":"0"},"500");
                            setTimeout(function(){
                                $(".c_container").css("display","none");
                            },500);
                            $(".success_alert").css("display","block");
                            setTimeout(function(){
                                $(".success_alert").css("display","none");
                            },3000);
                            getCartNum();
                        }
                    })
                }else{
                    post({
                        url:"/order/saveBuyNowProduct",
                        data:{productId:_id,specGroup:_specArr.toString(),num:$(".num .middle input").val()},
                        success:function(data){
                            console.log(data)
                            setCookie("mobile_cartId",data.cartId);
                            setCookie("orderCode",data.orderCode);
                            go("/mobileorder/index.html");
                        }
                    })
                }
            }
        }else{
            go("/login/index.html");
        }
    }else{
        $(".select_alert").css("display","block");
        setTimeout(function(){
            $(".select_alert").css("display","none");
        },3000)
    }
});

//显示已选择的规格
function showSpec(arr){
    arr = removeItem(arr);
    var str = "请选择规格";
    if(arr.length != 0){
        str = '已选择';
        for(var i=0;i<arr.length;i++){
            str += " " + arr[i];
        }
    }
    $(".c_main .spec").text(str);
}

//获取所选规格的价格与库存
function getPrice(arr){

    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i]==''){
            flag = false;
        }
    }

    if(flag){   //判断是否所有规格都选了
        post({
            url:"/product/getProductSkuInfo",
            data:{productId:_id,specGroup:arr.toString()},
            success:function(data){
                total = data.merchantTotal;
                $(".c_detail .price").html('价格：<span>￥'+(data.price).toFixed(2)+'</span>');
                $(".c_detail .total").html('库存'+data.total+'件');
                $(".num input").val(min);
                $(".num span").text("(可购买 "+total+" 件)");
                $(".visual").css("visibility","visible");

                if(total>0){
                    $(".c_main .btn").css({"opacity":"1","background-color":"#ea540a"});
                }else{
                    $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
                }
            }
        })
    }else{
        $(".visual").css("visibility","hidden");
        $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
    }
}

//改变购买数量
function changeNum(){

    //数量加1
    $(".num .add").click(function(){
        var num = parseInt($(".num .middle input").val());
        $(".num .add,.num .minus").css("opacity","1");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>=total){
                $(".num .middle input").val(total);
                $(".num .add").css("opacity","0.3");
            }else{
                $(".num .middle input").val(num+1);
            }
        }
    });

    //数量减1
    $(".num .minus").click(function(){
        var num = parseInt($(".num input").val());
        $(".num .minus").css("opacity","0.3");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>min){
                $(".num input").val(num-1);
                if(num-min > 1){
                    $(".num .minus").css("opacity","1");
                }
            }else{
                $(".num input").val(min);
            }
        }

    });

    //输入数量
    $(".num input").blur(function(){
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            var _val = $(this).val();
            if(isNaN(_val)||_val<=min){
                $(this).val(min);
                $(".num .minus").css("opacity","0.3");
            }else{
                $(".num .minus").css("opacity","1");
                var num = parseInt($(this).val());
                if(num>=total){
                    $(this).val(total);
                    $(".num .add").css("opacity","0.3");
                }else{
                    $(this).val(Math.ceil(_val));
                    $(".num .add").css("opacity","1");
                }
            }
        }
    });
}

//专题文章列表，此页面现已删掉文章列表
function articleList(flag){

    post({
        url:"/article/list",
        data:{"productId":_id,"page":{"pageNo":pageNum,"pageSize":"10"}},
        success:function(data){
            var _html = '';
            for(var i=0;i<data.list.length;i++){
                _html += '<div class="list" data-id="'+data.list[i]["id"]+'">';
                _html += '<img src="'+SERVER_CONTEXT_PATH+"/load/picture/"+data.list[i]["imageUrl"]+'"/>';
                _html += '<div class="title single">'+data.list[i]["title"]+'</div>';
                _html += '<div class="over"></div><div class="time">';
                _html += '<p class="left">'+data.list[i]["createTime"]+'</p>';
                _html += '<div class="right" data-title="'+data.list[i]["title"]+'" data-title="'+data.list[i]["imageUrl"]+'"></div></div></div>';
            }

            $(".life_main").append(_html);

            if(flag&&data.list.length<=0){
                $(".none").removeClass("tab");
                $(".life .life_main").addClass("tab");
            }else{
                $(".life .life_main").removeClass("tab");
                $(".none").addClass("tab");
            }

            $(".life_main .list img,.life_main .list .title").click(function(){
                setCookie("good_id",_id);
                go("/article/index.html?id="+$(this).parent().data("id")+"&share="+shareId );
            });
        }
    });
}

function isScroll(){
    window.onscroll = function () {
        //监听事件内容
        if(getScrollHeight() == getWindowHeight() + getDocumentTop()){
            //当滚动条到底时,这里是触发内容
            //异步请求数据,局部刷新dom
            pageNum++;
            //console.log(pageNum);
            setTimeout(function() {
                //articleList(false);
            }, 1000);
        }
    };
}

// 上拉加载
//文档高度
function getDocumentTop() {
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

//可视窗口高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//滚动条滚动高度
function getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}



//移除数组的空元素
function removeItem(arr){
    var newArr=[];
    for(var i=0;i<arr.length;i++){
        if(arr[i] != ""){
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

//判断数组是否有空元素
function isEmpty(arr){
    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i] == ""){
            flag = false;
        }
    }
    return flag;
}
